﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using ColdSun.Framework;

namespace ColdSun.Commons
{
    public class XmlUtility
    {
        public static string SerializeObject<T>(T obj)
        {
            if (obj == null) { return string.Empty; }
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                StringBuilder sb = new StringBuilder();

                //This will clear out default namespaces
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(String.Empty, String.Empty);

                //This is needed to get rid of the <?xml...>
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;

                XmlWriter xmlWriter = XmlTextWriter.Create(sb, settings);
                serializer.Serialize(xmlWriter, obj, ns);

                return sb.ToString();
            }
            catch (Exception ex)
            {
                Logger.Error("SerializeObject", ex);
                return string.Empty;
            }
        }

        public static T DeserializeObject<T>(string xml)
        {
            try
            {
                if (xml == null) xml = "";
                XmlSerializer xs = new XmlSerializer(typeof(T));
                XmlTextReader reader = new XmlTextReader(xml, XmlNodeType.Document, null);

                return (T)xs.Deserialize(reader);
            }
            catch (Exception ex)
            {
                Logger.Error("DeserializeObject" , ex);
                return default(T);
            }
        }
    }
}
